import DataBase from "better-sqlite3";
import logger from "./logger4js";

class BetterDbHelper {
  constructor() {
    this.db = new DataBase("./sqlite3.test.db");
  }
  log(sql, params) {
    if(logger.isDebugEnabled()) {
      logger.debug("SQL->", sql);
      logger.debug("PARAM->", params);
    }
  }
  queryRows(sql,params) {
    this.log(sql, params);
    return this.db.prepare(sql).all(params);
  }

  insert(sql, params) {
    return this.exec(sql, params);
  }

  update(sql, params) {
    return this.exec(sql, params);
  }

  delete(sql, params) {
    return this.exec(sql, params);
  }

  count(sql, params) {
    this.log(sql, params);
    const stmt = this.db.prepare(sql);
    stmt.pluck();
    return stmt.get(params);
  }

  getById(sql, params) {
    return this.db.prepare(sql).get(params);
  }

  exec(sql, params) {
    this.log(sql, params);
    return this.db.prepare(sql).run(params);
  }
}

export default new BetterDbHelper();

